package QC.MessageBox.handler;

import QC.MessageBox.annotation.MethodLog;
import QC.MessageBox.annotation.RouteMapping;
import QC.MessageBox.beans.appmsg.BaseAppMsg;
import QC.MessageBox.beans.wbmsg.WBTextMsg;
import QC.MessageBox.common.HttpUtils;
import QC.MessageBox.enums.SendResult;
import QC.MessageBox.exceptions.ParamException;
import QC.MessageBox.service.*;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Andaren on 2017/6/29.
 * Used for: 微博回复
 */
@RouteMapping(path = "/wb/message")
public class WeiBoReplyHandler extends HandlerBase {

    private static final Logger LOGGER = LoggerFactory.getLogger(WeiBoReplyHandler.class);

    private BlockingService blockingService;

    public WeiBoReplyHandler() {}

    public WeiBoReplyHandler(Map<String, Object> handlerMap) {
        Objects.requireNonNull(handlerMap);
        this.dataAccess = (DataAccess)handlerMap.get("dataAccess");
        this.httpService = (HttpService)handlerMap.get("httpService");
        this.sqlService = (MySQLService)handlerMap.get("mySQLService");
        this.redisService = (RedisService)handlerMap.get("redisService");
//        this.mongoService = (MongoService) handlerMap.get("mongoService");
        this.webClientService = (WebClientService)handlerMap.get("webClientService");
        this.blockingService = (BlockingService)handlerMap.get("blockingService");
    }

    @RouteMapping(path = "/back")
    @MethodLog("回复微博用户")
    public void replyWeiBoUser (RoutingContext context) {
        HttpServerResponse appResponse = context.response();

        String requestBodyStr = context.getBodyAsString();
        LOGGER.info(">>>received app msg -> {}", requestBodyStr);
        // BaseMsg
        BaseAppMsg baseAppMsg = null;
        try {
            baseAppMsg = new BaseAppMsg(requestBodyStr);
        } catch (UnsupportedEncodingException encodeExcep) {
            LOGGER.info("[{}]参数解码异常,error={}", "回复微博用户", encodeExcep.getMessage(), encodeExcep);
            HttpUtils.commonJsonResponse(appResponse, SendResult.FAILED_PARAM_DECODE.getResultJson(encodeExcep.getMessage()));
            return;
        } catch (ParamException pExcep) {
            HttpUtils.commonJsonResponse(appResponse, SendResult.FAILED_PARAM_DECODE.getResultJson(pExcep.getMessage()));
            LOGGER.info("[{}]参数异常,error={}", "回复微博用户", pExcep.getMessage(), pExcep);
            return;
        }

        // 验证请求参数
        if (!checkRequestParam(appResponse, baseAppMsg)) {
            return;
        }
        Future<Void> replyFuture = Future.future();
        replyWBMsg(baseAppMsg).setHandler(as -> {
            if (as.succeeded()) {
                HttpUtils.commonJsonResponse(appResponse, SendResult.SUCCESS.getResultJson(null));
                LOGGER.info("回复成功");
                replyFuture.complete();
            } else {
                HttpUtils.commonJsonResponse(appResponse, SendResult.FAILED_HANDLE.getResultJson(as.cause().getMessage()));
                LOGGER.info("回复微博用户失败：[{}]", as.cause().getMessage());
                as.cause().printStackTrace();
            }
        });
    }

    public Future<Void> replyWBMsg (final BaseAppMsg baseAppMsg) {
        Future<Void> replyFut = Future.future();
        dataAccess.getWXPublicInfoByDeveloperId(baseAppMsg.getDeveloperId())
                .compose(wxPublic -> {
                    WBTextMsg replyWBMsg = new WBTextMsg();
                    replyWBMsg.setReceiver_id(Long.valueOf(baseAppMsg.getOpenId()))
                            .setData(baseAppMsg.getContent())
                            .setType("text")
                            .setAccess_token(wxPublic.getAccessToken());
                    return webClientService.sendMsgToFans(wxPublic.getAccessToken(), replyWBMsg);
                }).setHandler(replyFut.completer());
        return replyFut;
    }

    /**
     * 检验请求参数
     * @param appResponse
     * @param baseAppMsg
     * @return
     */
    public boolean checkRequestParam(HttpServerResponse appResponse, BaseAppMsg baseAppMsg) {
        if (StringUtils.isBlank(baseAppMsg.getOpenId())) {
            HttpUtils.commonJsonResponse(appResponse, SendResult.FAILED_PARAM.getResultJson("openId为空"));
            return false;
        } else if (StringUtils.isBlank(baseAppMsg.getDeveloperId())) {
            HttpUtils.commonJsonResponse(appResponse, SendResult.FAILED_PARAM.getResultJson("developerId为空"));
            return false;
        } else if (StringUtils.isBlank(baseAppMsg.getType())) {
            HttpUtils.commonJsonResponse(appResponse, SendResult.FAILED_PARAM.getResultJson("type为空"));
            return false;
        } else if (StringUtils.isBlank(baseAppMsg.getContent())) {
            HttpUtils.commonJsonResponse(appResponse, SendResult.FAILED_PARAM.getResultJson("content为空"));
            return false;
        }
        return true;
    }
}
